package com.yenlien.traceyun.milk.service;

import com.yenlien.traceyun.milk.dao.MilkScreenDao;
import com.yenlien.traceyun.milk.entity.MilkScreen;
import com.yenlien.traceyun.milk.entity.Storage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Date 2023/8/25
 * @Author ChenXi
 * @Descript 总大屏奶站数据
 */
@Service
public class MilkScreenService {

    @Autowired
    private MilkScreenDao milkScreenDao;

    public Map<String, Object> findAll() {
        List<MilkScreen> all = milkScreenDao.findAll();
        //收奶量
        BigDecimal inSum = all.stream()
                .map(e -> e.getMilkYield() != null ? e.getMilkYield() : BigDecimal.ZERO)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 总金额 转换为万元，保留一位小数
        long amount = all.stream().mapToLong(e -> e.getMoney() != null ? e.getMoney() : 0).sum();
        BigDecimal priceSum = new BigDecimal(amount).divide(BigDecimal.valueOf(10000), 1, RoundingMode.HALF_UP);
        //农户数量
//        long farmerSum = farmersDao.findAll().stream().filter(x -> "1".equals(x.getState())).count();
        Map<String, Object> map = new HashMap<>();
        map.put("inNumSum", inSum + "kg");
        map.put("priceSum", priceSum + "万元");
        map.put("farmerSum", 13 + "个");
        return map;

    }

    public Page<MilkScreen> findPastureSort(Pageable pageable) {
        Page<MilkScreen> all = milkScreenDao.findAll(Specification.where(fieldNotNull("milkName")), pageable);
        return all;
    }

    public Specification<MilkScreen> fieldNotNull(String fieldName) {
        return (root, query, criteriaBuilder) ->
                criteriaBuilder.isNotNull(root.get(fieldName));
    }
}
